package io.gitee.gemini.utis;

import io.gitee.gemini.core.constants.StrConstants;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.UUID;

public class SeqUtil {

    /**
     * UUID序列
     *
     * @return 默认全大写的UUID
     */
    public static String uuid() {
        return uuid(true, true);
    }

    /**
     * 特殊处理的uuid
     *
     * @param noDash    不包含 -
     * @param upperCase 大写
     * @return 返回经过处理的UUID
     */
    public static String uuid(boolean noDash, boolean upperCase) {
        String uuid = UUID.randomUUID().toString();
        String result = uuid;
        if (upperCase) {
            result = result.toUpperCase(Locale.ROOT);
        }
        if (noDash) {
            result = result.replace(StrConstants.DASH, StrConstants.EMPTY);
        }
        return result;
    }

    /**
     * @param length 获取的序列长度，越短越容易重复
     * @return 随机串
     */
    public static String uniSeq(int length) {
        MessageDigest instance = null;
        try {
            instance = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] digest = instance.digest(uuid().getBytes());
        StringBuilder builder = new StringBuilder();
        for (byte b : digest) {
            builder.append(String.format("%02X", b));
        }
        return builder.substring(0, length);
    }


}
